//
//  JQFYLonginViewController.m
//  JQFY
//
//  Created by apple on 2017/8/6.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYLonginViewController.h"
#import "PPAlertController.h"
#import "PhonrNumber.h"
#import "JQFYTabbarController.h"
#import <AVFoundation/AVFoundation.h>
#import "JQFYSettingUserInfoViewController.h"
#import "JQFYBaseNavigationController.h"
#import "JQFYLoginWebViewController.h"

@interface JQFYLonginViewController ()
@property (nonatomic,strong)AVPlayer *player;
@property (nonatomic,strong)UIButton *loginButton;
@property (nonatomic,strong)UITextField *loginText;
@property (nonatomic,strong)UITextField *passwordText;
@property (nonatomic,strong)UIButton *codeBtn;
@property (nonatomic ,copy) NSString *codeStr;
@property (nonatomic,strong)UIButton *warnBtn;
@property (nonatomic ,strong) UIButton *dissBtn;

@end

@implementation JQFYLonginViewController

-(void)viewWillAppear:(BOOL)animated
{
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playVideos) name:@"appBecomeActive" object:nil];
    [self.player play];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [self.player pause];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupForAVplayerView];
    [self setupUI];
}

-(void)setupUI
{
    
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 263 *SCAL, 55 *SCAL)];
    img.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMinY(self.view.bounds) + 135 *SCAL);
    [img setImage:[UIImage imageNamed:@"logo"]];
//    UIImageView *logoImg = [[UIImageView alloc] initWithFrame:self.view.bounds];
//    [logoImg setImage:[UIImage imageNamed:@"loginBg"]];
//    [self.view addSubview:logoImg];
//    logoImg.userInteractionEnabled = YES;
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [self.view addSubview:img];
    [self.view addSubview:self.loginText];
    [self.view addSubview:self.passwordText];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.codeBtn];
    [self.view addSubview:self.warnBtn];
    [self.view addSubview:self.dissBtn];
    
//    [logoImg addSubview:self.loginText];
//    [logoImg addSubview:self.passwordText];
//    [logoImg addSubview:self.loginButton];
//    [logoImg addSubview:self.codeBtn];
    
    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    self.loginText.transform = CGAffineTransformTranslate(self.view.transform, 0, -height);
    self.passwordText.transform = CGAffineTransformTranslate(self.view.transform, 0, -height);
    self.codeBtn.transform = CGAffineTransformTranslate(self.view.transform, 0, -height);
    self.loginButton.transform = CGAffineTransformTranslate(self.view.transform, 0, -height);
    self.warnBtn.transform = CGAffineTransformTranslate(self.view.transform, 0, -height);
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    self.loginText.transform = CGAffineTransformIdentity;
    self.passwordText.transform = CGAffineTransformIdentity;
    self.codeBtn.transform = CGAffineTransformIdentity;
    self.loginButton.transform = CGAffineTransformIdentity;
    self.warnBtn.transform = CGAffineTransformIdentity;
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [self.view endEditing:YES];
}

-(UITextField *)loginText
{
    if (!_loginText) {
        _loginText = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 302 *SCAL, 42 *SCAL)];
        _loginText.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMaxY(self.view.bounds) - 200 *SCAL);
        [_loginText setPlaceholder:@"请输入您的手机号"];
        [_loginText setBackground:[UIImage imageNamed:@"phoneNum"]];
        [_loginText setTextAlignment:NSTextAlignmentCenter];
        [_loginText setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [_loginText setValue:[UIFont boldSystemFontOfSize:14 *SCAL] forKeyPath:@"_placeholderLabel.font"];
        _loginText.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _loginText;
}

-(UITextField *)passwordText
{
    if (!_passwordText) {
        _passwordText = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 302 *SCAL, 42 *SCAL)];
        _passwordText.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMaxY(self.view.bounds) - 140 *SCAL);
        [_passwordText setPlaceholder:@"请输入获取的验证码"];
        [_passwordText setBackground:[UIImage imageNamed:@"code"]];
        [_passwordText setTextAlignment:NSTextAlignmentCenter];
        [_passwordText setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [_passwordText setValue:[UIFont boldSystemFontOfSize:14 *SCAL] forKeyPath:@"_placeholderLabel.font"];
        _passwordText.keyboardType = UIKeyboardTypeNumberPad;
}
    return _passwordText;
}

-(UIButton *)loginButton
{
    if (!_loginButton) {
        _loginButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 302 *SCAL, 42 *SCAL)];
        _loginButton.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMaxY(self.view.bounds) - 80 *SCAL);
        [_loginButton setBackgroundImage:[UIImage imageNamed:@"loginBtnNew"] forState:UIControlStateNormal];
        [_loginButton setTitle:@"注 册 并 登 录" forState:UIControlStateNormal];
        [_loginButton.titleLabel setFont:[UIFont fontWithName:@"Verdana-Bold" size:15]];
        [_loginButton setTintColor:[UIColor whiteColor]];
        [_loginButton addTarget:self action:@selector(didClickBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

-(UIButton *)warnBtn
{
    if (!_warnBtn) {
        _warnBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200 *SCAL, 10 *SCAL)];
        _warnBtn.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMaxY(self.view.bounds) - 40 *SCAL);
        [_warnBtn setBackgroundImage:[UIImage imageNamed:@"loginWarnBtn"] forState:UIControlStateNormal];
        [_warnBtn addTarget:self action:@selector(didClickWarnBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _warnBtn;
}
//验证码
-(UIButton *)codeBtn
{
    if (!_codeBtn) {
        _codeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 65 *SCAL, 42 *SCAL)];
        _codeBtn.center = CGPointMake(CGRectGetMaxX(self.passwordText.bounds) + 4 *SCAL, CGRectGetMaxY(self.view.bounds) - 140 *SCAL);
        [_codeBtn setBackgroundImage:[UIImage imageNamed:@"getCode"] forState:UIControlStateNormal];
        [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_codeBtn.titleLabel setFont:[UIFont systemFontOfSize:10 *SCAL]];
        [_codeBtn.titleLabel setTextColor:[UIColor grayColor]];
        [_codeBtn addTarget:self action:@selector(didCodeBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeBtn;
}

//dissmissbtn
-(UIButton *)dissBtn{
    if (!_dissBtn) {
        _dissBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 20 *SCAL, 20 *SCAL)];
        [_dissBtn setBackgroundImage:[UIImage imageNamed:@"WechatIMG5"] forState:UIControlStateNormal];
        [_dissBtn addTarget:self action:@selector(didDissBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _dissBtn;

}
#pragma mark -
#pragma mark 点击事件

//dissmiss点击
-(void)didDissBtn{
    [self dismissViewControllerAnimated:YES completion:nil];
}
//验证码点击事件
-(void)didCodeBtn
{
    NSLog(@"点击了发送验证码");
    [self codeTime];
}
//点击警告用户须知
-(void)didClickWarnBtn{
    NSLog(@"点击警告");
    JQFYLoginWebViewController *webController = [[JQFYLoginWebViewController alloc]init];
    NSString *urlStr = @"http://app.uninhibited.cn/plan/user_notes.html";
    WKWebView *webView = [[WKWebView alloc] initWithFrame:webController.view.bounds];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
    [webController.view addSubview:webView];
    [self presentViewController:[[JQFYBaseNavigationController alloc] initWithRootViewController:webController] animated:YES completion:nil];
}
//登录点击
-(void)didClickBtn
{
    if (self.passwordText.text && self.loginText.text) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSDictionary *dic = @{@"name":self.loginText.text,@"code":self.passwordText.text};
        [manager POST:@"http://app.uninhibited.cn/api/user/manage" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"status"]isEqualToString:@"success"]) {
                //存入数据
                JQFYUserData *userData = [JQFYUserData sharedData];
                userData.token = responseObject[@"token"];
                userData.loginName = self.loginText.text;
                userData.isLogin = YES;
                [userData saveUserInfo];
                if ([responseObject[@"id"]isEqualToString:@"0"]){
                    JQFYSettingUserInfoViewController *settingVc = [[JQFYSettingUserInfoViewController alloc] init];
                    [self presentViewController:settingVc animated:YES completion:nil];
                }else{
                    JQFYTabbarController *tbVc = [[JQFYTabbarController alloc]init];
                    [self presentViewController:tbVc animated:YES completion:nil];
                }
                
            }else{
                //弹窗提示错误
                [PPAlertController alertWithTitle:@"请求错误" alertMessage:@"验证码错误" buttonTitles:nil alertVC:self selectButtonBlock:nil];
                NSLog(@"提示错误");
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求错误--%@",error);
        }];

    }else{
        [PPAlertController alertWithTitle:@"输入错误" alertMessage:@"请输入正确的验证码" buttonTitles:nil alertVC:self selectButtonBlock:^(NSInteger selectIndex) {
            self.passwordText.text =@"";
        }];
    }
}
//登录请求
-(void)getToken{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSArray *array = @[@{@"name":self.loginText.text},@{@"code":self.passwordText.text}];
    [manager POST:@"http://app.uninhibited.cn/api/user/manage" parameters:array progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"status"]isEqualToString:@"success"]) {
            NSLog(@"登录成功---%@",responseObject);
            //存入数据
            JQFYUserData *userData = [JQFYUserData sharedData];
            userData.token = responseObject[@"token"];
            userData.loginName = self.loginText.text;
            userData.isLogin = YES;
            NSLog(@"token----%@-----\n状态----%@",responseObject[@"token"],responseObject[@"status"]);
            [userData saveUserInfo];
            JQFYTabbarController *tbVc = [[JQFYTabbarController alloc]init];
            [self presentViewController:tbVc animated:YES completion:nil];
        }else{
            //弹窗提示错误
            [PPAlertController alertWithTitle:@"请求错误了啊打发斯蒂芬" alertMessage:@"验证码错误" buttonTitles:nil alertVC:self selectButtonBlock:nil];
            NSLog(@"提示错误");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求错误--%@",error);
    }];
    
}
//获取验验证码
-(void)getCode{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *dic = @{@"name":self.loginText.text};
    [manager POST:messageURL parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"status"] isEqualToString: @"success"]) {
            NSLog(@"成功获取验证码--%@",responseObject);
            JQFYUserData *data = [JQFYUserData sharedData];
            data.securityCode = responseObject[@"msg"];
            [data saveUserInfo];
        }else{
            //弹窗提示错误
            [PPAlertController alertWithTitle:@"输入错误" alertMessage:@"验证码已发送，请勿重复请求" buttonTitles:nil alertVC:self selectButtonBlock:nil];
            NSLog(@"提示错误");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败---%@",error);
    }];
}
//正则验证code 数字
- (BOOL) deptNumInputShouldNumber:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}

#pragma mark -
#pragma mark 音频播放相关

- (void)playVideos
{
    [self.player play];
}

- (void)setupForAVplayerView
{
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = self.view.bounds;
    [self.view.layer addSublayer:playerLayer];
}

- (AVPlayer *)player
{
    if (!_player) {
        AVPlayerItem *playerItem = [self getPlayItem];
        _player = [AVPlayer playerWithPlayerItem:playerItem];
        _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
        [[NSNotificationCenter defaultCenter]addObserver:self
                                                selector:@selector(playerItemDidPlayToEndTimeNotification:)
                                                    name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return _player;
}


-(AVPlayerItem *)getPlayItem
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"BridgeLoop-640p" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    return playerItem;
}

- (void)playerItemDidPlayToEndTimeNotification:(NSNotification *)sender
{
    [_player seekToTime:kCMTimeZero];
}

#pragma mark -
#pragma mark 验证码
// 验证码倒计时
-(void)codeTime{
    [self.codeBtn.titleLabel setFont:[UIFont systemFontOfSize:10 *SCAL]];
    int phoneNum = [PhonrNumber phoneNumberRight:_loginText.text];
    //判定手机号码
    if (phoneNum == 0) {
        //获取验证码请求
        [self getCode];
        //设置倒计时时间
        __block int timeout = 60;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout <= 0){ //倒计时结束重新获取
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.codeBtn.userInteractionEnabled = YES;
                    [self.codeBtn.titleLabel setFont:[UIFont systemFontOfSize:7 *SCAL]];
                    [self.codeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
                });
            }else{
                int seconds = timeout % 60;
                __block NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示
                    self.codeBtn.userInteractionEnabled = NO;
                    [self.codeBtn setTitle:[NSString stringWithFormat:@"%@s后重发",strTime] forState:UIControlStateNormal];
                });
                timeout--;
            }
        });
        dispatch_resume(_timer);
        
    }else{
        //弹窗提示错误
        [PPAlertController alertWithTitle:@"输入错误" alertMessage:@"请输入正确的手机号码" buttonTitles:nil alertVC:self selectButtonBlock:nil];
        self.loginText.text = @"";
        NSLog(@"提示错误");
    }
}
@end
